<?php
namespace App\Models\Tg;


use App\Models\Tg\TgGoods;

use App\Models\CheckoutConfig;

use App\Models\Goods\GoodsSale;

use App\Models\ConfigureFunction;

use App\Models\Goods\GoodsMaster;

use App\Models\Goods\GoodsPicture;

use App\Models\Goods\GoodsSpecRelation;

use App\Models\Activity\ActivityCommonMall;

use Illuminate\Support\Facades\Redis as Redis;

use Illuminate\Database\Eloquent\Model;

class Tg extends Model
{

    protected $table = 'promotion_tuan_master';

    protected $primaryKey = 'tuan_id';

    public $timestamps = false;

    public $incrementing = false;


    /**
     * 查询团购详情缓存
     * @param int $id 团购id
     * @return null|array
     */
    public static function getCache( $id )
    {

        if ( !isset($id) || empty($id) ) {
            return [];
        }

        //从redis中获取团购缓存数据
        $tg = redisTransformation(Redis::get('G_WDH_TG_' . $id));
        if ($tg) {
            return $tg;
        }

        /**
         * =============================================
         * redis中没有团购的缓存数据
         * 1. 查询团购信息
         * 2. 查询商品详情
         * 3. 查询商品图片链接地址
         * 4. 查询商品规格
         * 5. 查询团购商品信息
         * =============================================
         */

        //查询拼团商品信息
        $tg = Tg::find($id);
        if ( empty($tg) ) {
            return [];
        }
        $tg = $tg->toArray();

        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        //主商品号
        $mainPostID = $tg['mainPostID'];

        //结算配置id
        $checkout_config_id = $tg['checkout_config_id'];

        //查询主商品信息
        $goods_master = GoodsMaster::find($mainPostID);
        if( !$goods_master ){
            return [];
        }
        $tg['goods_photo_link'] = $goods_master->goodsMainPic;

        //商品详情
        $description = $goods_master->mobile_description;
        if ( !$description ) {
            $description = $goods_master->pc_description;
        }
        $tg['goods_description'] = empty($description)? '' : htmlspecialchars_decode($description);

        //三级网购号
        $tg['postID'] = $goods_master->postID;

        //价格
        $tg['salePrice'] = $goods_master->salePrice;

        //查询商品图片链接地址
        $tg['goods_pic'] = [];
        $pic = GoodsPicture::where('mainPostID', $mainPostID)->orderBy('sortOrder', 'ASC')->get()->toArray();
        if ($pic) {
            foreach ( $pic as &$p ) {
                if( empty( $p['pictureLink'] ) ) {
                    continue;
                }
                $tg['goods_pic'][] = $domain_url . $p['pictureLink'] ;
            }
        }

        //查询商品规格
        $tg['goods_spec'] = GoodsSpecRelation::getList($mainPostID);

        //查询团购商品信息
        $tg_goods = TgGoods::where('tuan_id', $id)->get()->toArray();

        $tg['goods'] = [];
        $tg['list'] = [];
        $spec_temp = [];
        if ( $tg_goods ) {

            foreach ( $tg_goods  as &$item ) {

                //商品规格组及名称
                $item['one_level_spec_str'] = '';
                $item['two_level_spec_str'] = '';
                $item['goodsID'] = '';
                $item['goodsName'] = '';
                $item['marketPrice'] = '';
                $item['salePrice'] = '';
                $item['spec'] = '';
                $item['specID'] = '';
                $item['goodsWeight'] = '';
                $item['goodsType'] = '';
                $item['img_link'] = '';
                $item['product_code'] = '';
                $item['product_spec'] = '';

                $sale_goods_data = GoodsSale::getCache($item['postID']);
                if( !$sale_goods_data ){
                    continue;
                }

                $item['goodsID'] = $sale_goods_data['goodsID'];
                $item['goodsName'] = $sale_goods_data['goodsName'];
                $item['marketPrice'] = $sale_goods_data['marketPrice'];
                $item['salePrice'] = $sale_goods_data['salePrice'];
                $item['spec'] = $sale_goods_data['spec'];
                $item['specID'] = $sale_goods_data['specID'];
                $item['goodsWeight'] = $sale_goods_data['goodsWeight'];
                $item['goodsType'] = $sale_goods_data['goodsType'];
                $item['img_link'] = $domain_url . $sale_goods_data['goodsMainPic'];
                $item['product_code'] = $sale_goods_data['product_code'];
                $item['product_spec'] = $sale_goods_data['product_spec'];

                /**
                 * 拆分商品规格，获取对应规格及规格组信息
                 */
                if ( $sale_goods_data['specID'] ) {

                    $spec_arr = explode(',', $sale_goods_data['specID']);
                    $one_level_spec_id = isset($spec_arr[0]) && ebsig_is_int($spec_arr[0]) ? $spec_arr[0] : 0;
                    $two_level_spec_id = isset($spec_arr[1]) && ebsig_is_int($spec_arr[1]) ? $spec_arr[1] : 0;

                    if ( $one_level_spec_id > 0 ) {
                        $spec_relation = GoodsSpecRelation::where('mainPostID', $sale_goods_data['mainPostID'])->where('specID', $one_level_spec_id)->get()->toArray();
                        $item['one_level_spec_str'] = $spec_relation[0]['specGroupName'] . '：' . $spec_relation[0]['specName'];
                    }

                    if ( $two_level_spec_id > 0 ) {
                        $spec_relation = GoodsSpecRelation::where('mainPostID', $sale_goods_data['mainPostID'])->where('specID', $two_level_spec_id)->get()->toArray();
                        $item['two_level_spec_str'] = $spec_relation[0]['specGroupName'] . '：' . $spec_relation[0]['specName'];
                    }

                    if ( $one_level_spec_id > 0 ) {
                        $spec_temp[0][] = $one_level_spec_id;
                    }

                    if ( $two_level_spec_id > 0 ) {
                        $spec_temp[1][] = $two_level_spec_id;
                    }

                }

                $temp_goods_spec_id = explode(',', $sale_goods_data['specID']);
                $spec_key = '';
                foreach ($temp_goods_spec_id as &$spec_id) {
                    if (!empty($spec_id)) {
                        $spec_key .= $spec_id;
                    }
                }
                if (empty($spec_key)) {
                    $spec_key = 0;
                }

                $tg['list'][$spec_key] = [
                    'id' => $item['postID'],
                    'enable_sale_amount' => 1000,
                    'salePrice' =>$sale_goods_data['salePrice'],
                    'price' => $item['tuan_price'],
                    'img_link' => $domain_url . $sale_goods_data['goodsMainPic'],
                ];

            }

        }

        $tg['goods'] = $tg_goods;

        //除去非活动商品中的规格
        if ( $tg['goods_spec'] ) {
            foreach ( $tg['goods_spec'] as $key => &$group ) {
                if ( isset($group['list']) && isset($spec_temp[$key]) && !empty($spec_temp[$key]) ) {
                    foreach ( $group['list'] as $k => $spec ) {
                        if ( !in_array($spec['id'], $spec_temp[$key]) ) {
                            unset($group['list'][$k]);
                        }
                    }
                }
            }
        }


        //查询拼团订单配置信息
        $tg['config'] = CheckoutConfig::find($checkout_config_id)->toArray();

        $tg['activity_mall'] = [];

        //判断是否是指定门店
        if ( $tg['config'] && $tg['config']['mall_range_type'] == 2 ) {
            $search_result = ActivityCommonMall::where('activity_id', $id)->get(['mall_id'])->toArray();
            if ( $search_result ) {
                foreach ( $search_result as &$item ) {
                    $tg['activity_mall'][] = $item['mall_id'];
                }
            }
        }

        Redis::setex('G_WDH_TG_' . $id, 604800, redisTransformation($tg, 'set',604800));

        return $tg;

    }

}
